package com.gulimall.cart.controller;

import com.alibaba.fastjson2.JSONObject;
import com.gulimall.cart.service.CartService;
import com.gulimall.cart.vo.CartVo;
import com.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * @author kkk
 * @date 2022/8/2
 */
@Controller
@Slf4j
public class CartController {
    @Autowired
    private CartService cartService;


    @GetMapping("/checkCartItem")
    @ResponseBody
    public R getCartCheckItem() {
        List<CartVo.CartItemVo> cartItemVos = cartService.getCheckItem();

        return R.ok().put("cartItems", JSONObject.toJSONString(cartItemVos));
    }

    @GetMapping("/changeCheck/{skuId}/{checked}")
    public String changeCheck(@PathVariable Long skuId, @PathVariable boolean checked) {
        cartService.changeItemCheck(skuId, checked);

        return "redirect:http://cart.gulimall.com/cartList.html";
    }

    @GetMapping("/changeCount/{skuId}/{count}")
    public String changeCount(@PathVariable Long skuId, @PathVariable Integer count) {
        cartService.changeItemCount(skuId, count);

        return "redirect:http://cart.gulimall.com/cartList.html";
    }

    /**
     * 删除购物车项
     *
     * @param skuId
     * @return
     */
    @GetMapping("/delItem/{skuId}")
    public String deleteItem(@PathVariable Long skuId) {
        cartService.deleteItem(skuId);

        return "redirect:http://cart.gulimall.com/cartList.html";
    }

    @GetMapping("/cartList.html")
    public String cartList(Model model) {
        CartVo cartVo = cartService.getCartList();

        model.addAttribute("cartList", cartVo);
        return "cartList";
    }

    /**
     * 添加商品到购物车
     *
     * @param skuId
     * @param count
     * @return
     */
    @GetMapping("/addProductToCart")
    public String addProductToCart(@RequestParam Long skuId, @RequestParam Integer count, RedirectAttributes ra) {
        cartService.addProduct(skuId, count);

        ra.addAttribute("skuId", skuId);

        return "redirect:http://cart.gulimall.com/addProductSuccess.html";
    }

    /**
     * 跳转到成功页
     *
     * @return
     */
    @GetMapping("addProductSuccess.html")
    public String addProductSuccess(@ModelAttribute("skuId") Long skuId, Model model) {
        CartVo.CartItemVo cartItemVo = cartService.getCartItem(skuId);

        model.addAttribute("cartItem", cartItemVo);
        return "success";
    }
}
